# -*- coding:utf-8 -*-
import web, models, service
from baseHandler import BaseHandler
from utils.decorator import render


class CompanyCases(BaseHandler):
    @render(None)
    def GET(self, branchCompanyId, _type):
        user = self.getCurrentUser()
        branchCompanyId = long(branchCompanyId)
        service.Company.getBranchCompany(branchCompanyId)
        hasOverviewRight = service.User.hasOverviewRight(user)

        if not hasOverviewRight and branchCompanyId != user.company_id:
            raise web.seeother('/company/%d/%s' % (user.company_id, _type))

        branchCompanys = models.Company.getBatchByType(models.Company.TYPE_BRANCH) if hasOverviewRight else [models.Company.getById(user.company_id)]

        data = {'branch_companys' : branchCompanys, 'active_company_id' : branchCompanyId, 'can_overview' : hasOverviewRight}
        if 'finished_cases' == _type:
            data['title'] = u'已结案清单'
            data['active_type'] = 'finished'
            data['viewPath'] = 'finishedCases.html'
            data['cases'] = service.Case.getFinishedFormatCases(branchCompanyId)
            return data
        elif 'unfinished_cases' == _type:
            data['title'] = u'未结案清单'
            data['active_type'] = 'unfinished'
            data['viewPath'] = 'unfinishedCases.html'
            data['cases'] = service.Case.getUnfinishedFormatCases(branchCompanyId)
            return data

    @render(None, 'json')
    def POST(self, branchCompanyId, _type):
        branchCompanyId = long(branchCompanyId)
        user = self.getCurrentUser()

        service.User.canOperate(user, branchCompanyId)

        service.Company.getBranchCompany(branchCompanyId)
        if models.User.TYPE_CHIEF != user.type:
            raise service.ServiceException.ServiceException(service.UNAUTHORIZED, '没有权限')

        value = long(float(web.input().get('value') or 0) * 100)
        _type = int(web.input().get('type') or 0)
        address = web.input().get('address')
        reason = web.input().get('reason')
        insurance_time = web.input().get('insurance_time')
        caseId = service.Operation.createCase(branchCompanyId, user.id, _type, address, reason, insurance_time, value)
        raise web.seeother('/company/%d/case/%d' % (branchCompanyId, caseId))